package com.eques.util

import android.app.ActivityManager
import android.app.Application
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.util.Log
import com.eques.database.base.AppDatabase
import com.eques.database.dao.DevListDao
import com.eques.database.dao.ShaowDao
import com.eques.icvss.utils.ELog
import com.eques.service.DoorBellService
import org.json.JSONObject
import java.io.IOException

class BaseAppApplication : Application() {
    private val TAG = BaseAppApplication::class.java.simpleName
    private var doorBellServiceIt: Intent? = null
    lateinit var preference: EquesPreference

    override fun onCreate() {
        super.onCreate()
        instance = this

        init()

        AppUtils.setApplication(this)
        // 启动服务
        startService()

        getServer()
    }

    /**
     * 获取设备列表数据库操作类
     */
     fun getYkDao(ctx:Context): DevListDao {
        val db = AppDatabase.build(ctx)
        return db.ykDao()
    }

    /**
     * 获取影子设置数据库操作类
     *
     */
    fun getShaowDao(ctx:Context): ShaowDao {
        val db = AppDatabase.build(ctx)
        return db.shaowDao()
    }

    /**
     * 获取服务器地址
     *
     * 通过发送GET请求到配置的服务器地址获取服务器信息，并解析响应数据
     * 将主服务器IP和备用服务器IP保存到本地偏好设置中
     *
     * @throws IOException 如果响应状态码意外
     */
    private fun getServer() {
        val url =Config.getServerUrl(Config.EQUES_DEFAULT_DISTRIBUTE_IP_PORT,
            Config.EQUES_SERVER_APPID.toString(),Config.EQUES_SERVER_APPKEY)
        ELog.e(TAG, "get server:$url")
        HttpUtil.getAsync(
            url = url.toString(),
        ) { result ->
            result.onSuccess { response ->
                println("GET Response: $response")
                var jsonObject = response.let { JSONObject(it) }
                // Extract the main and sub server IP from the JSON object
                val serverIp = jsonObject.optString("main")
                val serverNonIp = jsonObject.optString("sub")
                // Save the server IPs to local preferences
                preference.putString(Config.MAIN_ADDRESS, serverIp)
                preference.putString(Config.SUB_ADDRESS, serverNonIp)
            }.onFailure { exception ->
                println("GET Error: ${exception.message}")
            }
        }

    }
    private fun init() {
        preference= EquesPreference(this)
        HttpsUtils.initSslSocketFactory(null, null, null)
    }

    /**
     * 启动总的服务
     */
    private fun startService() {
        if (doorBellServiceIt == null) {
            doorBellServiceIt = Intent(this, DoorBellService::class.java)
        }
        val isMainServiceRunning: Boolean =
            serviceAtWorking(this, ActionUtils.ACTION_EQUES_SERVICE)
        if (!isMainServiceRunning) {
            Log.e(TAG, "start service")
            doorBellServiceIt!!.setType(packageName)
            bindService(doorBellServiceIt!!, conn, BIND_AUTO_CREATE)
        }
    }


    private val conn: ServiceConnection = object : ServiceConnection {
        override fun onServiceDisconnected(name: ComponentName) {
            Log.e(TAG, "onServiceDisconnected")
        }

        override fun onServiceConnected(name: ComponentName, service: IBinder) {
            Log.e(TAG, "onServiceConnected")
            // TODO Auto-generated method stub
            // 只有当我们自己写的MyService的onBind方法返回值不为null时，才会被调用
            if (service is DoorBellService.DoorBellBinder) {
                // 主服务绑定成功
                val doorBellBinder: DoorBellService.DoorBellBinder =
                    service as DoorBellService.DoorBellBinder
                val doorBellService: DoorBellService = doorBellBinder.service
                if (doorBellService != null) {
                    AppUtils.service = doorBellService
                }
            }
        }
    }

    /**
     * 应用程序结束时调用
     */
    override fun onTerminate() {
        super.onTerminate()
        // 解绑服务
        unbindService(conn)
    }

    companion object {
        var instance: BaseAppApplication? = null
            private set
    }

    /**
     * 服务是否在正常运行
     *
     * @param className
     * @param ctx
     * @return
     */
    fun serviceAtWorking(ctx: Context, className: String): Boolean {
        val myManager =
            ctx.applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningService = myManager.getRunningServices(Int.MAX_VALUE)
        if (runningService.size <= 0) {
            return false
        }
        for (runningServiceInfo in runningService) {
            if (runningServiceInfo.process == ctx.packageName && runningServiceInfo.service.className == className) {
                return true
            }
        }
        return false
    }

}
